﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;


public struct Point
{
	public int x,y;

	public Point(int x, int y)
	{
		this.x = x;
		this.y = y;
	}

	public static bool operator ==(Point a, Point b)
	{
		if (a.x == b.x && a.y == b.y)
			return true;
		return false;
	}

	public static bool operator !=(Point a, Point b)
	{
		return !(a == b);
	}
}

[ExecuteInEditMode]
public class TileMap : MonoBehaviour {


	public int Width
	{
		get
		{
			return 0;
		}
	}
	public int Height
	{
		get
		{
			return 0;
		}
	}
	public int NumberOfTiles
	{
		get
		{
			return map.Keys.Count;
		}
	}

	public bool showTransparent = false;
	public float alpha = 1f;

	Dictionary<Point, TileStack> map;

	public void Start()
	{
		InitializeMap();
	}

	public void OnEnable()
	{
		InitializeMap();
	}

	public void InitializeMap()
	{
		if(map == null)
			map = new Dictionary<Point, TileStack>();
	}

	public bool StillExistTile(int x, int y)
	{
		var pt = new Point(x, y);

		if (!map.ContainsKey(pt))
			return false;


		if (map[pt] == null || map[pt].gameObject == null)
		{
			map.Remove(pt);
			return false;
		}
		return true;
	}

	public void AddTile(int x, int y, GameObject prefab)
	{
		var pt = new Point(x, y);
		var tile = Instantiate(prefab) as GameObject;

		if (!StillExistTile(x,y))
		{

				var o = new GameObject();
				o.transform.parent = this.transform;
				o.transform.position = new Vector3(x + 0.5f, 0, y + 0.5f);

				var ts = o.AddComponent<TileStack>();
				ts.X = x;
				ts.Y = y;

				o.name = "(" + x + "," + y + ")";
				map.Add(pt, ts);
		}
		map[pt].AddTile(tile);
	}


	public int GetTileCountAt(int x, int y)
	{
		if (StillExistTile(x, y))
		{
			var pt = new Point(x,y);
			return map[pt].Count;
		}
		return 0;
	}
	//z = height
	//x,y = point location respected to map
	public void RemoveTile(int x, int y, int z)
	{
		var pt = new Point(x, y);

		if (StillExistTile(x, y))
		{
			map[pt].RemoveTile(z);

			if (map[pt].Count <= 0)
			{
				var o = map[pt].gameObject;

				map.Remove(pt);
				DestroyImmediate(o);
			}
		}
	}
}
